<?php
declare(strict_types=1);

namespace app\model;

use think\Model;
use think\facade\Cache;

class LifeServiceConfig extends Model
{
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    /**
     * 业务类型映射
     */
    public const BUSINESS_TYPE_MAP = [
        1 => '快递',
        2 => '滴滴打车',
        3 => '花小猪',
        4 => '美团',
        5 => '饿了么',
        6 => '淘宝',
        7 => '京东',
        8 => '拼多多',
        9 => '抖音',
        10 => '考拉',
        11 => '唯品会'
    ];

    /**
     * 获取业务类型名称
     */
    public function getBusinessTypeTextAttr($value, $data)
    {
        return self::BUSINESS_TYPE_MAP[$data['business_type']] ?? '未知';
    }

    /**
     * 获取利润率百分比
     */
    public function getProfitRatePercentAttr($value, $data)
    {
        return round($data['platform_profit_rate'] * 100, 1) . '%';
    }

    /**
     * 获取所有启用的利润率配置
     * @return array
     */
    public static function getProfitRates(): array
    {
        return Cache::remember('life_service_profit_rates', function() {
            $configs = self::where('status', 1)->column('platform_profit_rate', 'business_type');
            return $configs ?: [];
        }, 3600); // 缓存1小时
    }

    /**
     * 获取指定业务类型的利润率
     * @param int $businessType
     * @return float
     */
    public static function getProfitRate(int $businessType): float
    {
        $rates = self::getProfitRates();
        return floatval($rates[$businessType] ?? 0.2); // 默认20%
    }

    /**
     * 清除利润率缓存
     */
    public static function clearCache(): void
    {
        Cache::delete('life_service_profit_rates');
    }
} 